// AdvertisementPage.tsx - 修复后的版本
import React, { useContext, useEffect, useState, useCallback } from 'react';
import {
    Table,
    Button,
    Modal,
    Space,
    Card,
    Row,
    Col,
    Typography,
    Spin,
    Alert,
    message,
    Popconfirm
} from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import ProductADContext from '../context/ProductADContext';
import { type ProductAd } from '../api/service/ProductADService';
import { fileService } from "../api/service/FileService.tsx";
import ProductADForm from '../component/ProductADForm';

const { Title } = Typography;

const AdvertisementPage: React.FC = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingAd, setEditingAd] = useState<ProductAd | null>(null);
    const [imageUrls, setImageUrls] = useState<Record<string, string>>({});
    const [loadingImage, setLoadingImage] = useState<Record<string, boolean>>({});
    const productADContext = useContext(ProductADContext);

    if (!productADContext) {
        throw new Error('ProductADProvider must be used within ProductADProvider');
    }

    // 添加 fetchMoreAds 到解构
    const { ads, loading, error, deleteAd, fetchAds } = productADContext;

    // 获取广告图片URL - 使用 useCallback 优化
    const fetchImageUrl = useCallback(async (id: string, fileKey: string) => {
        // 如果已经有图片URL或者正在加载，则跳过
        if (imageUrls[id] || loadingImage[id]) {
            return;
        }

        try {
            // 设置加载状态
            setLoadingImage(prev => ({ ...prev, [id]: true }));

            // 获取下载URL
            const fileUrl = await fileService.getDownloadUrl(fileKey);
            if (fileUrl.url) {
                setImageUrls(prev => ({ ...prev, [id]: fileUrl.url! }));
            }
        } catch (error) {
            console.error('获取图片URL失败:', error);
            message.error('获取广告图片失败');
        } finally {
            setLoadingImage(prev => {
                const newLoading = { ...prev };
                delete newLoading[id];
                return newLoading;
            });
        }
    }, [imageUrls, loadingImage]);

    // 当广告列表变化时，获取所有图片URL
    useEffect(() => {
        ads.forEach(ad => {
            if (ad.coverAddr && !imageUrls[ad.id]) {
                fetchImageUrl(ad.id, ad.coverAddr);
            }
        });
    }, [ads, fetchImageUrl, imageUrls]);

    // 组件挂载时获取广告数据
    useEffect(() => {
        fetchAds();
    }, [fetchAds]);

    // 处理新建广告
    const handleCreate = () => {
        setEditingAd(null);
        setIsModalVisible(true);
    };

    // 处理编辑广告
    const handleEdit = async (ad: ProductAd) => {
        setEditingAd(ad);
        setIsModalVisible(true);

        // 如果还没有图片URL，获取一下
        if (ad.coverAddr && !imageUrls[ad.id]) {
            await fetchImageUrl(ad.id, ad.coverAddr);
        }
    };

    // 处理删除广告
    const handleDelete = async (id: string) => {
        try {
            const result = await deleteAd(id);

            if (result) {
                message.success('删除成功');
                // 清除对应的图片URL缓存
                setImageUrls(prev => {
                    const newUrls = { ...prev };
                    delete newUrls[id];
                    return newUrls;
                });
                // 清除加载状态
                setLoadingImage(prev => {
                    const newLoading = { ...prev };
                    delete newLoading[id];
                    return newLoading;
                });
                // 不再需要手动调用 refreshAds，因为 deleteAd 已经更新了本地状态
            } else {
                message.error('删除失败');
            }
        } catch (error) {
            console.error('广告删除失败:', error);
            message.error('删除失败: ' + (error instanceof Error ? error.message : '未知错误'));
        }
    };

    // 处理表单成功提交
    const handleFormSuccess = async () => {
        setIsModalVisible(false);
        setEditingAd(null);
        try {
            // 不再需要手动调用 refreshAds，因为 createAd 已经更新了本地状态
            message.success(editingAd ? '广告更新成功' : '广告创建成功');
        } catch (error) {
            console.error('操作失败:', error);
            message.error('操作失败: ' + (error instanceof Error ? error.message : '未知错误'));
        }
    };

    // 处理模态框取消
    const handleModalCancel = () => {
        setIsModalVisible(false);
        setEditingAd(null);
    };

    // 表格列定义
    const columns: ColumnsType<ProductAd> = [
        {
            title: '广告ID',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '商品ID',
            dataIndex: 'productId',
            key: 'productId'
        },
        {
            title: '封面图片',
            dataIndex: 'coverAddr',
            key: 'coverAddr',
            render: (_: string, record: ProductAd) => {
                const coverUrl = imageUrls[record.id];
                const isLoading = loadingImage[record.id];

                return (
                    <div style={{ width: '100px', height: '100px', position: 'relative' }}>
                        {isLoading ? (
                            <Spin />
                        ) : coverUrl ? (
                            <img
                                src={coverUrl}
                                alt="广告封面"
                                style={{ width: '100px', height: '100px', objectFit: 'cover' }}
                            />
                        ) : record.coverAddr ? (
                            // 有coverAddr但没有获取到URL，显示占位符
                            <div style={{
                                width: '100px',
                                height: '100px',
                                backgroundColor: '#f0f0f0',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                color: '#999'
                            }}>
                                加载中...
                            </div>
                        ) : (
                            // 没有coverAddr，显示无图片
                            <div style={{
                                width: '100px',
                                height: '100px',
                                backgroundColor: '#f0f0f0',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                color: '#999'
                            }}>
                                无图片
                            </div>
                        )}
                    </div>
                );
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (date: string) => new Date(date).toLocaleString()
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (date: string) => new Date(date).toLocaleString()
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: ProductAd) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确认删除"
                        description="确定要删除这个广告吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确认"
                        cancelText="取消"
                    >
                        <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <div style={{
            height: 'calc(100vh - 112px)',
            overflowY: 'auto',
            scrollbarWidth: 'thin', // Firefox
            scrollbarColor: '#c1c1c1 #f1f1f1' // Firefox
        }}>
            <style>
                {`
                /* Webkit浏览器滚动条样式 */
                div::-webkit-scrollbar {
                    width: 4px;
                }
                
                div::-webkit-scrollbar-track {
                    background: #f1f1f1;
                    border-radius: 10px;
                }
                
                div::-webkit-scrollbar-thumb {
                    background: #c1c1c1;
                    border-radius: 10px;
                }
                
                div::-webkit-scrollbar-thumb:hover {
                    background: #a8a8a8;
                }
                `}
            </style>
            <Card>
                <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
                    <Col>
                        <Title level={3}>商品广告管理</Title>
                    </Col>
                    <Col>
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={handleCreate}
                            loading={loading}
                        >
                            新建广告
                        </Button>
                    </Col>
                </Row>

                {error && (
                    <Alert
                        message="数据加载失败"
                        description={error}
                        type="error"
                        showIcon
                        style={{ marginBottom: 16 }}
                    />
                )}

                <Spin spinning={loading && ads.length === 0}>
                    <Table
                        columns={columns}
                        dataSource={ads}
                        rowKey="id"
                        pagination={false}
                    />
                </Spin>
            </Card>

            {/* 广告表单模态框 */}
            <Modal
                title={editingAd ? "编辑广告" : "新建广告"}
                open={isModalVisible}
                onCancel={handleModalCancel}
                footer={null}
                width={600}
            >
                <ProductADForm
                    ad={editingAd}
                    onCancel={handleModalCancel}
                    loading={loading}
                    onSuccess={handleFormSuccess}
                />
            </Modal>
        </div>
    );
};

export default AdvertisementPage;
